/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hu.sqlexpr;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author trekan
 */
public class SqlVisitor implements Visitor {

    protected StringBuilder sb = new StringBuilder();
    protected List<Object> bindings = new ArrayList<Object>();
    protected boolean whereStarted;

    public void visit(Select select) throws SyntaxException {
        
        sb.append("select ").append(select.select).append(" from ").append(select.from);
        if (select.startWith != null) {
            throw new SyntaxException("StartWith not supported in standard syntax!");
        }
        if (select.connectBy != null) {
            throw new SyntaxException("ConnectBy not supported in standard syntax!");
        }
        if (select.where != null) {
            whereStarted = true;
            select.where.accept(this);
        }
        if (select.orderBy != null) {
            sb.append(" order by ").append(select.orderBy);
        }
        if (select.paging != null) {
            throw new SyntaxException("Paging not supported in standard syntax!");
        }
    }

    public void visit(Condition con) throws SyntaxException {
        if (whereStarted && con.bool) {
            sb.append(" where ");
        }
        if (con.bool) {
            sb.append(con.condition);
            if (con.binding != null) {
                bindings.add(con.binding);
            }
        }
        if (con.and != null) {
            if (con.bool) {
                sb.append(" and ");
            }
            con.and.accept(this);
        }
        if (con.or != null) {
            if (con.bool) {
                sb.append(" or ");
            }
            con.or.accept(this);
        }
    }

    public void visit(Binding binding) {
        bindings.add(binding);
    }

    public void visit(Paging paging) {
    }

    public List<Object> getBindings() {
        return bindings;
    }

    public String getSql() {
        return sb.toString();
    }
    
}
